﻿using Quartz;
using SX.Core;
using SX.Data;
using SX.Utils;
using SX.Utils.Log.log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ly.Scheduler.Common
{
    /// <summary>
    /// 同步整车电池关系信息
    /// </summary>
    [DisallowConcurrentExecution]
    public class SyncProductBatteryJob : IJob
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(SyncProductBatteryJob));
        public void Execute(IJobExecutionContext context)
        {
            logger.Info("开始同步整车电池关系信息");
            var lydb = Db.Context("LYDB");
            var lyNewdb = Db.Context("LYNew");
            List<dynamic>  dataList = lydb.Sql(@"SELECT  DISTINCT b.ProductCode,b.BatteryCode,b.BatteryName,b.BatterySpec,b.BatteryQty,b.ConfigType
FROM    Product AS a
        INNER JOIN ProductBattery AS b ON a.ProductCode = b.ProductCode
WHERE   a.ProductCode LIKE '_____00__'
        AND b.BatteryCode != '105000085'  AND a.Discontinued =0").QueryMany<dynamic>();
            foreach (dynamic data in dataList)
            {
                string ProductCode = CommonHelper.ToString(data.ProductCode);
                string BatteryCode = CommonHelper.ToString(data.BatteryCode);
                string BatteryName = CommonHelper.ToString(data.BatteryName);
                string BatterySpec = CommonHelper.ToString(data.BatterySpec);
                int BatteryQty = CommonHelper.ToInt(data.BatteryQty);
                int ConfigType = CommonHelper.ToInt(data.ConfigType);
                
                lyNewdb.Sql(@"insert into wh_product2battery(product_code, battery_code,battery_name,battery_spec,battery_amount,whb_cfg_type,whb_status)
                    values(@product_code,@battery_code,@battery_name,@battery_spec,@battery_amount,@whb_cfg_type,@whb_status) ON CONFLICT(product_code,battery_code) 
                    do update 
                    set product_code=EXCLUDED.product_code, 
                    battery_name=EXCLUDED.battery_name,
                    battery_spec=EXCLUDED.battery_spec,
                    battery_amount=EXCLUDED.battery_amount,
                    whb_cfg_type=EXCLUDED.whb_cfg_type,
                    whb_status=EXCLUDED.whb_status;  ")
                .Parameter("product_code", ProductCode, DataTypes.String)
                .Parameter("battery_code", BatteryCode, DataTypes.String)
                .Parameter("battery_name", BatteryName, DataTypes.String)
                .Parameter("battery_spec", BatterySpec, DataTypes.String)
                .Parameter("whb_cfg_type", ConfigType, DataTypes.Int32)
                .Parameter("battery_amount", BatteryQty, DataTypes.Int32)
                .Parameter("whb_status", 0, DataTypes.Int32)  
                .Execute();
            } 
            logger.Info("同步整车电池关系完成");
        } 
    }
}
